package me.thinkjet.controller;

import com.jfinal.core.Controller;
import com.jfinal.ext.render.DwzRender;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import me.thinkjet.auth.AuthManager;
import me.thinkjet.model.Activity;
import me.thinkjet.model.News;
import me.thinkjet.service.TagService;
import me.thinkjet.service.UserService;

@ControllerBind(controllerKey = "/news", viewPath = "/news")
public class NewsController extends Controller {
	public void index() {
		int page = getParaToInt("pageNum", 1);
		int numPerPage = getParaToInt("numPerPage", 20);
		boolean hot = getParaToBoolean("hot", false);
		Page<News> news = News.dao.paginate(page, numPerPage, "select *",
				"from news" + (hot ? " where hot=1" : ""));
		for (News n : news.getList()) {
			n.put("tags", TagService.getNewsTags(n.getLong("id"), false));
			n.put("author_name",
					new UserService().findUserByUId(n.getLong("author"))
							.getStr("name"));
		}
		setAttr("news", news);
	}

	public void add() {

	}

	public void hot() {
		News n = News.dao.findById(getParaToLong());
		n.set("hot", !n.getBoolean("hot")).update();
		render(DwzRender.success());
	}

	public void edit() {
		setAttr("news", News.dao.findById(getParaToLong()));
	}

	public void update() {
		if (getModel(News.class).update()) {
			render(DwzRender.closeCurrentAndRefresh("news_index"));
		} else {
			render(DwzRender.error());
		}
	}

	public void create() {
		News a = getModel(News.class);
		a.set("author", AuthManager.getSessionUser(this).getUser().get("id"));
		a.save();
		render(DwzRender.closeCurrentAndRefresh("news_index"));
	}

	public void delete() {
		News.dao.deleteById(this.getPara());
		render(DwzRender.success());
	}


}
